package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：sean
 * @date ：Created in 2022/4/19
 * @description ：
 * @version: 1.0
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal>
	implements SetmealService {

	@Autowired
	private SetmealDishService setmealDishService;

	@Override
	@Transactional
	public void saveWithDish(SetmealDto setmealDto) {
		//扩展方法

		//保存套餐基本信息
		this.save(setmealDto);
		//保存套餐菜品关系
		List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();

		List<SetmealDish> setmealDishList = setmealDishes.stream().map((item) -> {
			item.setSetmealId(setmealDto.getId());
			return item;
		}).collect(Collectors.toList());
		setmealDishService.saveBatch(setmealDishList);
	}

	@Transactional
	@Override
	public void removeWithDish(List<Long> ids) {
		LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
		setmealLambdaQueryWrapper.in(Setmeal::getId,ids);
		setmealLambdaQueryWrapper.eq(Setmeal::getStatus,1);
		int count = this.count(setmealLambdaQueryWrapper);
		if (count>0){
			throw new CustomException("套餐有关联菜品，不能删除");
		}
		this.removeByIds(ids);
		LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper =new LambdaQueryWrapper<>();
		setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
		setmealDishService.remove(setmealDishLambdaQueryWrapper);
	}
}